/*
 * @Author       : lijia
 * @FilePath     : /resume-duck/src/config/language.tsx
 * @Description  :
 */
import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import { languageValueList } from './language'

/**
 * 使用接口获取语言文件
 * @param lng
 * @returns
 */
const getLocaleJSON = async (lng: LanguageValueType) => {
  return await fetch(`${import.meta.env.VITE_STATIC_PUBLIC_URL}/locale/${lng}.json`).then((res: any) => {
    return res && res.json()
  }).then((data: any) => {
    return data
  }).catch((err: any) => {
    console.error(err)
    let emptyLocale: LocaleType = {}
    for (let i in languageValueList) {
      emptyLocale[languageValueList[i]] = {}
    }
    return emptyLocale
  })
}

/**
 * 遍历语言列表，获取语言文件
 */
const resources: any = await (async () => {
  let _resources: any = {}
  for (let i in languageValueList) {
    _resources[languageValueList[i]] = await getLocaleJSON(languageValueList[i])
  }
  console.info(_resources)
  return _resources
})()

/**
 * i18n 初始化
 */
i18n.use(initReactI18next).init({
  resources,
  lng: languageValueList[0],
  fallbackLng: languageValueList[0],
  ns: ['components', 'components.form', 'home', 'todo', 'note', 'mine'],
  // defaultNS: 'home',
  interpolation: {
    escapeValue: false // react already safes from xss
  }
})

export default i18n
